package cn.datawin.spider.httputil;


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.entity.mime.content.StringBody;

public class HttpResponse {

	public static final int S_OK = 200;
	public static final int S_NOT_MODIFIED = 304;
	public static final int S_BAD_REQUEST = 400;
	public static final int S_NOT_AUTHORIZED = 401;
	public static final int S_FORBIDDEN = 403;
	public static final int S_NOT_FOUND = 404;
	public static final int S_NOT_ACCEPTABLE = 406;
	public static final int S_INTERNAL_SERVER_ERROR = 500;
	public static final int S_BAD_GATEWAY = 502;
	public static final int S_SERVICE_UNAVAILABLE = 503;
	/**
	 * 状态码
	 */
	private int responseCode;

	/**
	 * 状态消息
	 */
	private String responseMessage;

	/**
	 * 回复头
	 */
	private Map<String, String> headers = new HashMap<String, String>();

	/**
	 * 返回的cookies
	 */
	private Map<String, String> cookies = new HashMap<String, String>();;

	/**
	 * 数据流
	 */
	private byte[] responseData;
	
	private String charset = "UTF-8";

	/**
	 * 构造函数
	 * 
	 * @param responseCode
	 * @param responseMessage
	 */
	public HttpResponse(int responseCode, String responseMessage) {
		this.responseCode = responseCode;
		this.responseMessage = responseMessage;
	}

	public HttpResponse() {
	}

	/**
	 * @return the responseCode
	 */
	public int getResponseCode() {
		return responseCode;
	}

	/**
	 * @return the responseMessage
	 */
	public String getResponseMessage() {
		return responseMessage;
	}

	public void setHeader(String key, String value) {
		headers.put(key, value);
	}

	/**
	 * 返回所有的回复头的值
	 * 
	 * @return the headerFields
	 */
	public Map<String, String> getHeaders() {
		return headers;
	}

	public void setCookies(Map<String, String> cookies) {
		this.cookies = cookies;
	}

	public void setCookie(String key, String value) {
		this.cookies.put(key, value);
	}

	public Map<String, String> getCookies() {
		return cookies;
	}

	/**
	 * 返回指定名字的回复头的值 可能有多个返回值时，默认返回第一个值 header 可能重复,
	 * 
	 * @param name
	 * @return
	 * 
	 *         public String getHeader(String name) { List<String> list =
	 *         getHeaders(name); if (list != null && list.size() > 0) { return
	 *         list.get(0); } else { return null; } }
	 */

	/**
	 * 返回指定名字的所有的回复头的值的列表
	 * 
	 * @param name
	 * @return
	 */
	public String getHeader(String name) {
		return this.headers.get(name);
	}

	/**
	 * @return the inputStream
	 */
	public InputStream getRespInputsStream() {
		return new ByteArrayInputStream(responseData);
	}
	
	public void setResponseData(byte[] responseData) {
		this.responseData = responseData;
	}

	public byte[] getResponseData() {
		return responseData;
	}

	public String getResponseString() {
		return getResponseString(getCharset());
	}

	/**
	 * 获取回复的字符串
	 * @param charset
	 *  字符集编码
	 * @return
	 */
	public String getResponseString(String charset) {
		try {
			return new String(responseData, charset);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public long getContentLength() {
		String length = getHeader("Content-Length");
		return length != null ? Long.parseLong(length) : 0;
	}

	public String getContentType() {
		return getHeader("Content-Type");
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public String getCharset() {
		String content_type = getHeader("Content-Type");
		String charset =  getCharset(content_type);
		if(charset == null) charset = getCharset(getResponseString("ISO-8859-1")); 
		return charset == null ? this.charset : charset;
	}
	
    private final static Pattern patternForCharset = Pattern.compile("charset\\s*=\\s*['\"]*([^\\s;'\"]*)");

    public String getCharset(String contentType) {
    	if(contentType == null) return null;
        Matcher matcher = patternForCharset.matcher(contentType.toLowerCase());
        if (matcher.find()) {
            String charset = matcher.group(1);
            if (Charset.isSupported(charset)) {
                return charset;
            }
        }
        return null;
    }

}
